package main

import (
	"encoding/json"
	"fmt"
	weather "gitee.com/Andy_y_li/services/weather"
	"github.com/go-martini/martini"
	"github.com/russross/blackfriday"
	"io/ioutil"
	"net/http"
	"os"
)

type WeatherInfo map[string]string

func main() {
	m := martini.Classic()
	m.Get("/", index)

	m.Get("/weather/:city", func(params martini.Params, w http.ResponseWriter) error {
		return getWeather(params, w)
	})
	m.RunOnAddr(":9090")
}

func index(w http.ResponseWriter, r *http.Request) string {
	input := readFile("./README.md")
	output := blackfriday.MarkdownCommon([]byte(input))

	return string(output)
}

func readFile(path string) string {
	fi, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer fi.Close()
	fd, err := ioutil.ReadAll(fi)
	// fmt.Println(string(fd))
	return string(fd)
}

func getWeather(params martini.Params, w http.ResponseWriter) error {
	city := params["city"]
	data, err := query(city)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return err
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	return json.NewEncoder(w).Encode(data)
}

func query(city string) (WeatherInfo, error) {
	wCode, err := weather.GetWeatherCodeByCounty(city)
	if err != nil {
		fmt.Println(err)
		return WeatherInfo{}, err
	}
	qstr := "http://www.weather.com.cn/data/cityinfo/" + wCode + ".html"
	//fmt.Println(qstr)
	resp, err := http.Get(qstr)
	if err != nil {
		return WeatherInfo{}, err
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return WeatherInfo{}, err
	}
	//str := string(body)
	var s map[string]WeatherInfo
	//fmt.Println(str)
	err = json.Unmarshal(body, &s)
	if err != nil {
		return WeatherInfo{}, err
	}
	info := s["weatherinfo"]
	//fmt.Println(info)
	//fmt.Println(info["weather"])

	return info, nil
}
